<template>
  <div class="personal-center">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <i class="iconfont icon-book"></i>
        <span>考研真题训练系统</span>
      </div>
      <div class="user-info">
        <span class="welcome">欢迎回来，{{ userStore.username }}</span>
        <el-avatar :size="40" :src="userInfo.avatar"></el-avatar>
      </div>
    </header>

    <!-- 主体内容 -->
    <div class="main-container">
      <!-- 侧边导航 -->
      <div class="sidebar">
        <div class="user-card">
          <el-avatar :size="80" :src="userInfo.avatar"></el-avatar>
          <div class="user-details">
            <h3>{{ userStore.username }}</h3>
            <p>VIP {{ userInfo.vipLevel }} 会员</p>
            <p>积分: {{ userInfo.points }}</p>
          </div>
        </div>

        <el-menu
          default-active="2"
          class="side-menu"
        >
          <el-menu-item index="1" >
            <router-link to="/personal-center/info" class="menu-link">
              <i class="iconfont icon-user"></i>
              <span>个人信息</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="2" class="active">
            <router-link to="/personal-center/edit" class="menu-link">
              <i class="iconfont icon-edit"></i>
              <span>修改资料</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="3">
            <router-link to="/personal-center/feedback" class="menu-link">
              <i class="iconfont icon-message"></i>
              <span>消息反馈</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="4">
            <router-link to="/personal-center/notifications" class="menu-link">
              <i class="iconfont icon-notification"></i>
              <span>通知设置</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="5">
            <router-link to="/personal-center/cancel-account" class="menu-link">
              <i class="iconfont icon-logout"></i>
              <span>注销账户</span>
            </router-link>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 主内容区 -->
      <div class="content">
        <!-- 修改资料 -->
        <div class="edit-section">
          <h2 class="section-title">修改资料</h2>
          <div class="edit-form">
            <el-form :model="editForm" ref="editFormRef" label-width="100px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="editForm.username"></el-input>
              </el-form-item>
              
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email"></el-input>
              </el-form-item>
              
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="editForm.phone"></el-input>
              </el-form-item>
              
              <el-form-item label="性别" prop="gender">
                <el-select v-model="editForm.gender" placeholder="请选择性别">
                  <el-option label="男" value="male"></el-option>
                  <el-option label="女" value="female"></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="学校" prop="school">
                <el-input v-model="editForm.school"></el-input>
              </el-form-item>
              
              <el-form-item label="目标院校" prop="targetSchool">
                <el-input v-model="editForm.targetSchool"></el-input>
              </el-form-item>
              
              <el-form-item label="考试年份" prop="examYear">
                <el-date-picker
                  v-model="editForm.examYear"
                  type="year"
                  value-format="yyyy"
                  placeholder="选择考试年份">
                </el-date-picker>
              </el-form-item>
              
              <el-form-item label="头像">
      <el-upload
        class="avatar-uploader"
        :action="uploadAvatarUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        
        <!-- 如果已有头像则显示头像 -->
        <img 
          v-if="editForm.avatar" 
          :src="editForm.avatar" 
          class="avatar">
        
        <!-- 如果没有头像则显示上传图标 -->
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input 
                  type="password" 
                  v-model="editForm.newPassword" 
                  placeholder="输入新密码（留空则不修改）"
                  show-password></el-input>
              </el-form-item>
              
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input 
                  type="password" 
                  v-model="editForm.confirmPassword" 
                  placeholder="再次输入新密码"
                  show-password></el-input>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveProfile">保存修改</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '@/store/user'
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'EditProfile',
  setup() {
    const userStore = useUserStore()
    
    onMounted(() => {
      userStore.initialize()
    })
    
    return {
      userStore
    }
  },
  data() {
    return {
      userInfo: {
        id: null,
        username: '',
        email: '',
        phone: '',
        avatar: '',
        gender: '',
        school: '',
        targetSchool: '',
        examYear: '',
        vipLevel: 3,
        points: 1280
      },
      editForm: {
        id: null,
        username: '',
        email: '',
        phone: '',
        avatar: '',
        gender: '',
        school: '',
        targetSchool: '',
        examYear: '',
        newPassword: '',
        confirmPassword: ''
      },
      uploadAvatarUrl: 'http://localhost:8080/userpro/uploadAvatar'
    };
  },
  created() {
    this.fetchUserInfo();
  },
  methods: {
    // 获取用户信息
    async fetchUserInfo() {
      try {
        // 从store获取用户ID
        const userId = this.userStore.id;
        if (!userId) {
          ElMessage.error('无法获取用户ID');
          return;
        }
        
        const response = await axios.get('/api/user/find?id=${userId}', {
          params: { id: userId }
        });
        
        if (response.data) {
          this.userInfo = response.data;
          // 初始化编辑表单
          this.editForm = {
            id: this.userInfo.id,
            username: this.userInfo.username,
            email: this.userInfo.email,
            phone: this.userInfo.phone,
            avatar: this.userInfo.avatar,
            gender: this.userInfo.gender,
            school: this.userInfo.school,
            targetSchool: this.userInfo.targetSchool,
            examYear: this.userInfo.examYear,
            newPassword: '',
            confirmPassword: ''
          };
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败');
      }
    },
    
    // 头像上传成功处理
    handleAvatarSuccess(response, file) {
      if (response && response.startsWith('/uploads/')) {
        // 构建完整的头像URL
        const baseUrl = process.env.VUE_APP_API_BASE_URL || '';
        const avatarUrl = baseUrl + response;
        
        // 更新表单中的头像URL
        this.editForm.avatar = avatarUrl;
        
        // 立即更新UI中的头像
        this.userInfo.avatar = avatarUrl;
        
        // 更新store中的头像
        this.userStore.setAvatar(avatarUrl);
        
        ElMessage.success('头像上传成功');
      } else {
        ElMessage.error('头像上传失败: ' + (response.message || '未知错误'));
      }
    },
    
    // 头像上传前的验证
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isImage) {
        ElMessage.error('只能上传图片格式文件!');
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
      }
      
      return isImage && isLt2M;
    },
    
    // 保存资料
    async saveProfile() {
      // 验证密码一致性
      if (this.editForm.newPassword && this.editForm.newPassword !== this.editForm.confirmPassword) {
        ElMessage.error('两次输入的密码不一致');
        return;
      }
      
      try {
        // 准备更新数据
        const updateData = {
          id: this.editForm.id,
          username: this.editForm.username,
          email: this.editForm.email,
          phone: this.editForm.phone,
          avatar: this.editForm.avatar,
          gender: this.editForm.gender,
          school: this.editForm.school,
          targetSchool: this.editForm.targetSchool,
          examYear: this.editForm.examYear
        };
        
        // 1. 更新基本资料
        await axios.put('/userpro/updateProfile', updateData);
        
        // 2. 如果有新密码，更新密码
        if (this.editForm.newPassword) {
          await axios.put('/userpro/updatePassword', {
            id: this.editForm.id,
            password: this.editForm.newPassword
          });
        }
        
        // 更新store中的用户信息
        this.userStore.setUser({
          username: this.editForm.username,
          avatar: this.editForm.avatar
        });
        
        // 更新本地用户信息
        this.userInfo = { ...this.userInfo, ...updateData };
        
        // 清空密码字段
        this.editForm.newPassword = '';
        this.editForm.confirmPassword = '';
        
        ElMessage.success('个人信息更新成功');
      } catch (error) {
        console.error('更新个人信息失败:', error);
        ElMessage.error('更新个人信息失败: ' + (error.response?.data?.message || '未知错误'));
      }
    },
    
    // 重置表单
    resetForm() {
      this.editForm = {
        id: this.userInfo.id,
        username: this.userInfo.username,
        email: this.userInfo.email,
        phone: this.userInfo.phone,
        avatar: this.userInfo.avatar,
        gender: this.userInfo.gender,
        school: this.userInfo.school,
        targetSchool: this.userInfo.targetSchool,
        examYear: this.userInfo.examYear,
        newPassword: '',
        confirmPassword: ''
      };
      ElMessage.info('表单已重置');
    }
  }
};
</script>

<style scoped>

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.personal-center {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background: linear-gradient(135deg, #1e5799 0%,#207cca 100%);
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
}

.logo .iconfont {
  font-size: 28px;
  margin-right: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.welcome {
  margin-right: 15px;
  font-size: 14px;
}

.main-container {
  display: flex;
  max-width: 1400px;
  margin: 20px auto;
  padding: 0 20px;
}

.sidebar {
  width: 260px;
  margin-right: 20px;
}

.user-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.user-details h3 {
  margin: 15px 0 5px;
  font-size: 18px;
}

.user-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.side-menu {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.side-menu .iconfont {
  margin-right: 10px;
  font-size: 18px;
}

.side-menu .el-menu-item {
  cursor: pointer;
}

.side-menu .el-menu-item.active {
  background-color: #ecf5ff;
  color: #409EFF;
}

.content {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  color: #303133;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.edit-form {
  max-width: 600px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
